package com.sihan.swvp.action.sys;

import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lowagie.text.pdf.codec.Base64;
import com.sihan.swvp.action.BaseAction;
import com.sihan.swvp.common.CommonUtil;
import com.sihan.swvp.common.IpUtil;
import com.sihan.swvp.common.MD5Util;
import com.sihan.swvp.common.RandomImageGenerator;
import com.sihan.swvp.common.SessionContext;
import com.sihan.swvp.common.StringUtil;
import com.sihan.swvp.entity.sys.User;
import com.sihan.swvp.entity.sys.UserConfig;
import com.sihan.swvp.service.sys.ConfigService;
import com.sihan.swvp.service.sys.LogService;
import com.sihan.swvp.service.sys.MenuService;
import com.sihan.swvp.service.sys.UserService;
@Controller
@RequestMapping("/user")
public class UserAction extends BaseAction{
	@Autowired
	UserService userService;
	@Autowired
	public LogService logService;

	@Autowired
	public ConfigService configService;
	
	@Autowired
	MenuService menuService;
	
	/**
	 * 获取用户列表
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getUser")
	public Object getUser(){
		try {
			Map<String,Object> params = new HashMap<String,Object>();
//			params.put("eid", getParameter("eid"));
//			params.put("tj", getParameter("tj"));
//			params.put("dept", getParameter("dept"));
			String detps = getParameter("depts");
			String detp = getParameter("dept");
			if(!"0".equals(detp)){
				boolean s = detp != null && !"".equals(detp);
				boolean ss = detps != null && !"".equals(detps);
				
				if(s && ss)
				{
					detps = detps+","+detp;
				}
				if(!ss)
				{
					detps = detp;
				}
			}else{
				detps = null;
			}
			
			params.put("depts", detps);
			params.put("tj", getParameter("tj"));
			List<Map<String, Object>> list = userService.getUser(params);

			return list;
		} catch (Exception e) {
			return failMsg("服务器异常");
		}
	}

	/**
	 * 获取部门
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getEnterprise")
	public Object getEnterprise(){
		try {
			
			return userService.getEnterprise();
		} catch (Exception e) {
			
			return failMsg("服务器异常");
		}
	}

	/**
	 * 添加用户
	 * @param user 用户
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/addUser")
	public Object addUser(@ModelAttribute User user){
		String msg = "保存成功！";
		boolean l = user.getId() == null?false:true;
		try {
			User cu = (User) getSession().getAttribute("u");
			user.setUpdateuser(cu.getId());
			if(CommonUtil.isEmptyString(user.getId())){
				if(userService.userNameIsExistence(user.getAccount(),null) > 0){
					return failMsg("此用户账号已存在！");
				}
				user.setPassword(MD5Util.reversibleMD5Encode(user.getPassword()));
				userService.addUser(user);	
			}
			else{
				User ou = userService.getUserById(user);
//				if(null != ou && !ou.getPassword().equals(user.getPassword())){
//					user.setPassword(null);
//				}
				if(userService.userNameIsExistence(user.getAccount(),user.getId()) > 0){
					return failMsg("此用户账号已存在！");
				}
				userService.udpateUser(user);
				if(user.getId() == getLoginUser().getId()){
					getSession().setAttribute("u", user);
				}
			}
		} catch (Exception e) {
			logService.addUserLog(l?"修改":"添加", "用户", getLoginUser().getId(), l?"修改用户："+user.getName()+"("+user.getAccount()+")":"添加用户："+user.getName()+"("+user.getAccount()+")",getRemoteAddr(),0,1);
			return failMsg("服务器异常");
		}
		logService.addUserLog(l?"修改":"添加", "用户", getLoginUser().getId(), l?"修改用户："+user.getName()+"("+user.getAccount()+")":"添加用户："+user.getName()+"("+user.getAccount()+")",getRemoteAddr(),1,1);

		return successMsg(msg);
	}


	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value="/deleteUser")
	public Object deleteUser(@RequestParam String ids,@RequestParam String username){
		try {
			if(ids.toString().equals(getLoginUser().getId().toString())){
				logService.addUserLog("删除", "用户", getLoginUser().getId(), "删除用户："+username+"与当前操作用户一致",getRemoteAddr(),0,1);
				return successMsg("删除失败。删除用户与当前操作用户一致！");
			}
			
			userService.deleteUser(getLoginUser(),ids);
			SessionContext.getInstance().removeUsers((List<Long>) CommonUtil.split(ids,",",Long.class));
		} catch (Exception e) {
			e.printStackTrace();
			logService.addUserLog("删除", "用户", getLoginUser().getId(), "删除用户(批量)："+username,getRemoteAddr(),0,1);
			return failMsg("服务器异常");
		}

		logService.addUserLog("删除", "用户", getLoginUser().getId(), "删除用户(批量)："+username,getRemoteAddr(),1,1);
		
		return successMsg("删除成功");
	}
	
	@ResponseBody
	@RequestMapping(value="/setUser")
	public Object setUser(@Param("id")Integer id,
			@Param("name")String name,
			@Param("account")String account,
			@Param("passtime")Integer passtime,
			@RequestParam("enableip")String enableip,
			@Param("lockcount")Integer lockcount,
			@RequestParam("logintimestart")Date logintimestart,
			@RequestParam("logintimeend")Date logintimeend){
		Map<String, Object> datamap = new HashMap<String, Object>();
		datamap.put("id", id);
		datamap.put("passtime", passtime);
		datamap.put("enableip", enableip);
		datamap.put("lockcount", lockcount);
		datamap.put("logintimestart", logintimestart);
		datamap.put("logintimeend", logintimeend);
		try {
			userService.setUser(datamap);
			logService.addUserLog("设置用户", "用户", getLoginUser().getId(), "设置用户："+account+"("+name+")",getRemoteAddr(),1,1);
			return successMsg("保存成功");
		} catch (Exception e) {
			e.printStackTrace();
			logService.addUserLog("设置用户", "用户", getLoginUser().getId(), "设置用户："+name,getRemoteAddr(),0,1);
			return failMsg("服务器异常");
		}
	}

	@ResponseBody
	@RequestMapping(value="/selectUserByAccount")
	public Object selectUserByAccount(String account){
		User user = userService.selectUserByAccount(account);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(user.getOverduetime());
		int overdueday = calendar.get(Calendar.DAY_OF_YEAR);
		calendar.setTime(new Date());
	    int nowday = calendar.get(Calendar.DAY_OF_YEAR);
	    if(nowday - overdueday > user.getPasstime()){
	    	return 1;
	    }else {
			return 0;
		}
	}
	
	@RequestMapping(value="/login")
	@ResponseBody
	public Object login(HttpServletResponse response){
		String account = getParameter("account");
		String password = getParameter("password");
		//String vcode = getParameter("vcode");
		String aespass = MD5Util.reversibleMD5Encode(password);
		User user = userService.getUser(account, aespass);
		User userdata = userService.selectUserByAccount(account);
		try {
//			if(CommonUtil.isEmptyString(vcode)){
//				return failMsg("验证码不能为空。");
//			}
			if(userdata == null){
				return failMsg("用户名不存在，你确认后在登录。"); 
			}
			if(null == user){
				if(userdata.getLoginerrorcount()+1 < userdata.getLockcount()){
					userService.updateLoginErrorCount(userdata.getId(),userdata.getLoginerrorcount()+1);
					int secount = userdata.getLockcount()-userdata.getLoginerrorcount()-1;
					logService.addUserLog("登录", "用户", userdata.getId(), userdata.getName()+"("+userdata.getAccount()+")密码错误",getRemoteAddr(),0,1);
					return failMsg("用户名或密码不正确。还有"+secount+"次机会，总共输错"+userdata.getLockcount()+"次后将呗锁定。");
				}else if(userdata.getLoginerrorcount()+1 >= userdata.getLockcount()){
					userService.updateUserLocked(userdata.getId());
					logService.addUserLog("连续登录失败", "用户", userdata.getId(), userdata.getName()+"("+userdata.getAccount()+")连续登陆失败锁定",getRemoteAddr(),0,1);
					logService.addUserLog("锁定", "用户", userdata.getId(), userdata.getName()+"("+userdata.getAccount()+")锁定",getRemoteAddr(),1,1);
					return failMsg("您已"+userdata.getLockcount()+"次输错密码，账号暂时锁定，请20分钟后再试。");
				}
			}else{
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(user.getLogintimestart());
				int startday = calendar.get(Calendar.DAY_OF_YEAR);
				calendar.setTime(user.getLogintimeend());
				int endday = calendar.get(Calendar.DAY_OF_YEAR);
				calendar.setTime(new Date());
			    int nowday = calendar.get(Calendar.DAY_OF_YEAR);
				if(user.getLocked() == 0){//锁定
					long interval = ((new Date().getTime() - user.getLockedtime().getTime()))/(1000*60);
					if(interval <= 20){
						logService.addUserLog("登录", "用户", user.getId(), user.getName()+"("+user.getAccount()+")已锁定",getRemoteAddr(),0,1);
						return failMsg("账号暂时锁定，请20分钟后再试。");
					}else {
						userService.updateLoginErrorCount(user.getId(),0);
						userService.updateUserRemoveLocked(user.getId());
						userService.updateConn(user.getId(), 1);
						List<Map<String, Object>> menulist = menuService.getMenuByUserId(user.getId());
						getSession().setAttribute("logintime", new Date());
						getSession().setAttribute("config", userService.getConfig(user));
						getSession().setAttribute("u", user);
						getSession().setAttribute("menu", menulist);
						int maxsession = configService.getConfig().getMaxsession() * 60;
						getSession().setMaxInactiveInterval(maxsession);
						logService.addUserLog("登录", "用户", getLoginUser().getId(), user.getName()+"("+user.getAccount()+")",getRemoteAddr(),1,1);
						return successMsg();
					}
//				}else if(!getRemoteAddr().contains(user.getEnableip())){
//					logService.addUserLog("ip变动过大", "用户", user.getId(), user.getName()+"("+user.getAccount()+")登陆ip变动过大",getRemoteAddr(),0,1);
//					return failMsg("请在允许的ip："+user.getEnableip()+"上登陆");
				}else if(nowday < startday || nowday > endday){
					logService.addUserLog("登录", "用户", user.getId(), user.getName()+"("+user.getAccount()+")登陆时间不符",getRemoteAddr(),0,1);
					return failMsg("该账号不在允许登陆的时间范围内，请联系管理员");
				}else if(userService.getConnCount()+1 > configService.getConfig().getMaxconcurrent()){
					logService.addUserLog("登录", "用户", user.getId(), user.getName()+"("+user.getAccount()+")超出最大登陆数",getRemoteAddr(),0,1);
					return failMsg("已超出最大允许登陆账号数，请联系管理员！");
				}
				else if(user.getIsconn() == 1){
				logService.addUserLog("登录", "用户", user.getId(), userdata.getName()+"("+userdata.getAccount()+")重复登录",getRemoteAddr(),0,1);
					return failMsg("该账号已在其他设备登录！");
				}
				else{
					userService.updateLoginErrorCount(user.getId(),0);
					userService.updateConn(user.getId(), 1);
					List<Map<String, Object>> menulist = menuService.getMenuByUserId(user.getId());
					getSession().setAttribute("logintime", new Date());
					getSession().setAttribute("config", userService.getConfig(user));
					getSession().setAttribute("u", user);
					getSession().setAttribute("menu", menulist);
					int maxsession = configService.getConfig().getMaxsession() * 60;
					getSession().setMaxInactiveInterval(maxsession);
					logService.addUserLog("登录", "用户", getLoginUser().getId(), user.getName()+"("+user.getAccount()+")",getRemoteAddr(),1,1);
					return successMsg();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return failMsg("服务器异常");
		}
		return failMsg("用户名或密码不正确。");

	} 

	@RequestMapping(value="/logout")
	@ResponseBody
	public void logout(HttpSession session){
		Object u = session.getAttribute("u");
		if(null != u){
			User user = (User) u;
			userService.updateConn(user.getId(), 0);
			logService.addUserLog("注销", "用户", getLoginUser().getId(), user.getName()+"("+user.getAccount()+")",getRemoteAddr(),1,1);
		}
		
		session.removeAttribute("u");
		session.removeAttribute("logintime");
		
	} 

	@ResponseBody
	@RequestMapping(value="/getConfig")
	public Object getConfig(){

		return getSession().getAttribute("config");
	}


	@ResponseBody
	@RequestMapping(value="/getDefaultConfig")
	public Object getDefaultConfig(){

		return new UserConfig();
	}

	@ResponseBody
	@RequestMapping(value="/saveConfig")
	public Object saveConfig(){
		try {
			String cfg = getParameter("configs");
			String cf = cfg.replaceAll("“", "\"");
			//String cf = StringUtil.qj2bj(cfg);
			System.out.println(cf);
			JSONObject jcfg = (JSONObject) JSONObject.parse(cf);
			userService.saveConfig(getSession(),jcfg);
            String diy = "";
			if(cfg.contains("ext-all.css")){
				diy = "系统默认";
			}else if(cfg.contains("ext-all-slate.css")){
				diy = "板岩";
			}else if(cfg.contains("ext-all-gray1.css")){
				diy = "灰色";
			}else if(cfg.contains("ext-all-green.css")){
				diy = "绿色";
			}else if(cfg.contains("ext-all-pink.css")){
				diy = "粉红";
			}else if(cfg.contains("ext-all-purple.css")){
				diy = "紫色";
			}else if(cfg.contains("ext-all-red.css")){
				diy = "红色";
			}
			logService.addUserLog("更新", "个性化", getLoginUser().getId(), "系统皮肤更改为："+diy,getRemoteAddr(),1,1);
		} catch (Exception e) {
			e.printStackTrace();
			return failMsg("服务器异常");
		}

		return successMsg("");
	}
	/**
	 * 获取时时个性化设置数据
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getIndividuality")
	public Object getIndividuality(){
		return userService.getConfig(getLoginUser());
	}


	@ResponseBody
	@RequestMapping(value="/getVimg")
	public void getVimg(HttpServletResponse response,@RequestParam(required = true) String id){
		ServletOutputStream output = null;
		InputStream in = null;
		try {
			output = response.getOutputStream();

			String code = RandomImageGenerator.render(output, 70, 32);
			output.flush();
			output.close();
			getSession().setAttribute("vcode", code.toUpperCase());
		} catch (IOException e) {
			e.printStackTrace();
		} 
		finally{
			CommonUtil.close(output);
			CommonUtil.close(in);
		}
	}

	@ResponseBody
	@RequestMapping(value="/changePwd")
	public Object changePwd(){
		User user = getLoginUser();
		String oldpwd = getParameter("oldpwd");
		String newpwd0 = getParameter("newpwd0");
		String newpwd1 = getParameter("newpwd1");
		String vcode = getParameter("vcode");
		Object svcode = getSession().getAttribute("vcode");
		String aespass = MD5Util.reversibleMD5Encode(oldpwd);
		try {
			if(newpwd1.length() < 8){
				return failMsg("密码长度至少8位。");
			}
			if(!user.getPassword().equals(aespass)){

				return failMsg("密码不正确。");
			}
			else if(!newpwd0.equals(newpwd1)){

				return failMsg("新密码两次输入不一致。");
			}
			else if(!vcode.equals(svcode)){

				return failMsg("验证码不正确。");
			}
			else{
				User cu = (User) getSession().getAttribute("u");
				user.setUpdateuser(cu.getId());
				user.setPassword(MD5Util.reversibleMD5Encode(newpwd1));
				userService.udpateUser(user);
				//addUser(user);
				logService.addUserLog("修改密码", "用户", getLoginUser().getId(), "修改密码:"+user.getName()+"("+user.getAccount()+")",getRemoteAddr(),1,1);
				return successMsg();
			}

		} catch (Exception e) {
			e.printStackTrace();
			return failMsg("服务器异常");
		}

	}
	
	@ResponseBody
	@RequestMapping("/userNameIsExistence")
	public int userNameIsExistence(@RequestParam String userName){
		int n = userService.userNameIsExistence(userName,null);
		return n;
	}
	
	@ResponseBody
	@RequestMapping("/getUserLoginCount")
	public String getUserLoginCount(@RequestParam String userid){
		String conut = userService.getUserLoginCount(userid);
		return conut;
	}
	
	 

}
